package com.itheima.web.controller.cargo;

import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import com.itheima.domain.cargo.*;
import com.itheima.service.cargo.*;
import com.itheima.utils.DownloadUtil;
import com.itheima.vo.InvoiceVo;
import com.itheima.web.controller.BaseController;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.List;

@Controller
@RequestMapping("/cargo/invoice")
public class InvoiceController extends BaseController {
    @Reference
    private PackingService packingService;
    @Reference
    private ExportService exportService;
    @Reference
    private ContractService contractService;
    @Reference
    private ShippingOrderService shippingOrderService;
    @Reference
    private ExportProductService exportProductService;
    @Reference
    private InvoiceService invoiceService;
    @Reference
    private FinanceService financeService;
    @RequestMapping(value = "/list", name = "发票列表查询")
    public String list(@RequestParam(value = "page", defaultValue = "1") Integer pageNum,
                       @RequestParam(defaultValue = "10") Integer pageSize) {
        InvoiceExample invoiceExample = new InvoiceExample();
        PageInfo pageInfo = invoiceService.findByPage(pageNum, pageSize, invoiceExample);
        request.setAttribute("page",pageInfo);
        return "cargo/invoice/invoice-list";
    }
    @RequestMapping(value = "/toInvoice",name = "跳转生成发票页面")
    public String  toInvoice(String id){
        //查询对应的装箱单
        Packing packing = packingService.findById(id);
        //报运单号
        String exportIds = packing.getExportIds();
        String[] split = exportIds.split(",");
        String contractIds = "";
        Double invoiceMoney = 0.0;
        for (String exportId : split) {
            Export export = exportService.findById(exportId);
            String contractId = export.getContractIds();
            //报运合同id号生成
            contractIds = contractIds + " " + contractId;
            ExportProductExample exportProductExample = new ExportProductExample();
            exportProductExample.createCriteria().andExportIdEqualTo(exportId);
            List<ExportProduct> exportProductList = exportProductService.findAll(exportProductExample);
            for (ExportProduct exportProduct : exportProductList) {
                //发票金额
               double i = exportProduct.getCnumber() * exportProduct.getBoxNum() * exportProduct.getTax();
                invoiceMoney += i;
            }
        }
        //贸易条款
        String[] contractId = contractIds.split(" ");
        System.out.println(Arrays.toString(contractId));
        Contract contract = contractService.findById(contractId[1]);
        String tradeTerms = contract.getTradeTerms();
        InvoiceVo invoiceVo = new InvoiceVo();
        invoiceVo.setContractIds(contractIds);
        invoiceVo.setInvoiceMoney(invoiceMoney);
        invoiceVo.setTradeTerms(tradeTerms);
        request.setAttribute("invoiceVo",invoiceVo);
        request.setAttribute("id", id);
        return "cargo/invoice/invoice-toInvoice";
    }
    @RequestMapping(value = "/toView", name = "跳转查看发票单页面")
    public String toView(String id) {
        Invoice invoice = invoiceService.findById(id);
        request.setAttribute("invoice",invoice);
        return "cargo/invoice/invoice-view";
    }

    @RequestMapping(value = "/edit",name = "生成发票页面或修改")
    public String  edit(String shippingOrderId,Invoice invoice){
        //设置id
        invoice.setInvoiceId(shippingOrderId);
        //设置发票编号
        Packing packing = packingService.findById(shippingOrderId);
        invoice.setScNo(packing.getInvoiceNo());
        //设置状态
        invoice.setState(0);
        //设置创建人信息
        invoice.setCreateBy(getLoginUser().getUserName());
        invoice.setCreateDept(getLoginUser().getDeptName());
        invoiceService.save(invoice);
        //修改委托单状态
        ShippingOrder shippingOrder = shippingOrderService.findById(shippingOrderId);
        shippingOrder.setState(1);
        shippingOrderService.update(shippingOrder);
        return "redirect:/cargo/invoice/list.do";
    }
    @RequestMapping(value = "/findInvoiceState", name = "更新发票单状态")
    public String findInvoiceState(String id) {
        Finance finance = financeService.findById(id);
        if (finance == null){
            Invoice invoice = invoiceService.findById(id);
            invoice.setState(0);
            invoiceService.update(invoice);
        }
        return "redirect:/cargo/invoice/list.do";
    }
    @RequestMapping(value = "/delete", name = "发票单删除")
    public String delete(String id) {
        invoiceService.delete(id);
        return "redirect:/cargo/invoice/list.do";
    }
    @RequestMapping(value = "/invoiceExcel", name = "生成发票单表格")
    public void invoiceExcel(String id) throws IOException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-hh");
        Packing packing = packingService.findById(id);
        Invoice invoice = invoiceService.findById(id);
        ShippingOrder shippingOrder = shippingOrderService.findById(id);
        //读取模板
        String realPath = session.getServletContext().getRealPath("make/xlsprint/tINVOICE.xls");
        Workbook workbook = new HSSFWorkbook(new FileInputStream(new File(realPath)));
        Sheet sheet = workbook.getSheetAt(0);
        Row row3 = sheet.getRow(3);
        row3.createCell(0).setCellValue(packing.getSeller());
        row3.getCell(5).setCellValue("大脸猫皮具外贸有限公司");
        Row row8 = sheet.getRow(8);
        row8.createCell(0).setCellValue(packing.getBuyer());
        Row row15 = sheet.getRow(15);
        row15.createCell(0).setCellValue(packing.getInvoiceNo());
        String invoiceDate = format.format(packing.getInvoiceDate());
        row15.createCell(2).setCellValue(invoiceDate);
        row15.createCell(9).setCellValue(invoice.getBlNo());
        Row row19 = sheet.getRow(19);
        row19.createCell(5).setCellValue(shippingOrder.getPortOfLoading());
        row19.createCell(7).setCellValue(shippingOrder.getPortOfDischarge());
        Row row23 = sheet.getRow(23);
        row23.createCell(0).setCellValue(packing.getMarks());
        row23.createCell(2).setCellValue(packing.getDescriptions());
        Row row26 = sheet.createRow(26);
        row26.createCell(5).setCellValue("408");
        row26.createCell(6).setCellValue("PCS");
        row26.createCell(7).setCellValue("USD2.80");
        row26.createCell(9).setCellValue("USD" + invoice.getInvoiceMoney());
        Row row27 = sheet.createRow(27);
        row27.createCell(9).setCellValue("USD" + invoice.getInvoiceMoney());
        //下载
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        workbook.write(byteArrayOutputStream);
        DownloadUtil.download(byteArrayOutputStream,response,"发票表.xls");
    }
}
